<template>
  <page-wrap :show-top="true" :customWrapStyle="customWrapStyle" :title="'职业大全'" bgColor="#fff" back hideTab
    class="pageWrap">
    <view class="wrapper" :style="'padding-top:' + navHeight + 'px;'" type="line">
      <view class="header">
        <view class="search">
          <u-search placeholder="搜索您感兴趣的职业" class="library-u-search" v-model="keyword" height="80" bg-color="#F7F8FA;"
            :search-icon="searchIcon" @blur="handleSearchBlur" @change="handleSearch"
            @search="handleSearch($event, 'enter')" @custom="handleSearch" maxlength="20"
            :show-action="false"></u-search>
        </view>
        <scroll-view :scroll-y="true" class="searchResult" v-if="isSearching && keyword && searchResultList.length">
          <view class="resultList" v-if="searchResultList.length">
            <view class="resultItem" v-for="(item, index) in searchResultList" :key="index"
              @click="handleResultClick(item,'search')">
              <view class="resultTitle">
                <template v-for="(_item, _index) in item.filterList">
                  <text v-if="_item.deep" class="light" :key="_index">{{
                    _item.val
                  }}</text>
                  <template v-else>{{ _item.val }}</template>
                </template>
              </view>
              <view class="resultDesc">{{ item.topName ? item.topName + " - " : ""
                }}{{ item.parentName ? item.parentName : "" }}</view>
            </view>
          </view>
        </scroll-view>
        <view class="noneResult" v-if="isSearching && !searchResultList.length">
          <image :src="emptyImg" class="empty_image"></image>
          <view class="empty-title">
            暂无精准匹配职业，请重新输入职业关键字
          </view>
        </view>
      </view>
      <view class="beforeSearch" v-if="!keyword">
        <scroll-view :scroll-y="true" class="searchBox">
          <!-- 历史记录 -->
          <view class="searchHistoryContainer" v-if="searchHistory && searchHistory.length">
            <view class="historyTitle">
              <text class="left">搜索历史</text>
              <view class="right">
                <u-button :plain="true" @click="handleDeleteClick" class="deleteButton">
                  <image :src="deleteIcon" class="deleteIcon"></image>
                </u-button>
              </view>
            </view>
            <view class="historyContent">
              <view class="hisItem" v-for="(item,index) in showSearchHistory" @click="handleTagClick(item.text)"
                :key="index">
                <text>{{item.text}}</text>
              </view>
              <image :src="moreOpen" v-if="!showMoreHis && hasMoreBthHis" @click="handleOpenClick"></image>
              <image :src="moreClose" v-if="showMoreHis && hasMoreBthHis" @click="handleOpenClick"></image>
            </view>
          </view>
          <!-- 排行top10 -->
          <view class="topHot">
            <view class="title">
              <image :src="hotIcon"></image>热搜职业榜
            </view>
            <view class="hotList">
              <view class="hotItem" v-for="(item,index) in hotPositionList" @click="handleResultClick(item,'hot')"
                :key="item.positionId">
                <text class="sort" :class="index < 3?'origin':''">{{index+1}}</text>
                <view class="info">
                  <text class="descT ellipsis">{{item.tagTitle?item.tagTitle:''}}</text>
                  <text class="desc ellipsis">{{item.positionDesc?item.positionDesc:'一览热搜职业榜'}}</text>
                </view>
              </view>
            </view>
          </view>
        </scroll-view>
      </view>
    </view>
    <u-loading-page :loading="loading"></u-loading-page>
  </page-wrap>
</template>

<script>
import {
  matchPositionListNew,
  getHotPositionList,
  addPositionTopicPoint,
  getPositionTemplate,
} from "@/api/modules/career";
import share from "@/mixins/share";
export default {
  mixins: [share],
  name: "allCategory",
  data() {
    return {
      loading: false,
      navHeight: 0,
      searchIcon: this.$imgBaseSelf + "common/search.png",
      hotIcon: this.$imgBaseSelf + "common/hot.png",
      moreClose: this.$imgBaseSelf + "common/moreClose.png",
      moreOpen: this.$imgBaseSelf + "common/moreOpen.png",
      emptyImg: this.$imgBaseSelf + "common/empty.png",
      keyword: "",
      isSearching: false,
      searchResultList: [],
      customWrapStyle: {
        maxHeight: "100vh",
        overflow: "hidden",
        minHeight: "auto !important",
      },
      status: "loading",
      shareTitle: "职业大全", // 分享自定义标题
      sharePath: "/pages/career/positionDictionary/allCategory", // 分享自定义路径
      imageUrl: "",
      searchHistory: [],
      showSearchHistory: [],
      hasMoreBthHis: false, //搜索历史 是否显示 展开/收起 按钮
      showMoreHis: false, //搜索历史是否展开/收起
      deleteIcon: this.$imgBaseSelf + "common/delete.png",
      isOpen: false,
      hotPositionList: [],
    };
  },
  onLoad() {
    this.toggleHistoryData();
  },
  created() {
    this.navHeight = getApp().globalData.navHeight;
    this.showSearchHistory =
      (uni.getStorageSync("searchPosHistory") &&
        JSON.parse(uni.getStorageSync("searchPosHistory"))) ||
      [];
    this.searchHistory =
      (uni.getStorageSync("searchPosHistory") &&
        JSON.parse(uni.getStorageSync("searchPosHistory"))) ||
      [];
    this.getHotPositionList();
  },
  mounted() {},
  onReachBottom() {},
  methods: {
    async addPositionTopicPointFn(eventType,dataId) {
      const params = {
        eventType: eventType,
        dataId: dataId,
        personId: uni.getStorageSync("person-id").slice(2) || "0",
        description: "中学生高考点击了职业",
        platform: "1",
      };
      const res = await addPositionTopicPoint(params);
    },
    // 截取两行历史记录
    toggleHistoryData() {
      let idx = 0;
      let count = 0;
      let obj = uni.createSelectorQuery();
      obj
        .selectAll(".hisItem")
        .boundingClientRect()
        .exec((rect) => {
          if (rect) {
            rect[0].forEach((item, index) => {
              if (item.left <= 32) {
                count++;
                if (count === 3) {
                  idx = index - 1;
                  this.hasMoreBthHis = true;
                }
              }
            });
          }
          // 超过2行截断数据
          if (idx > 0) {
            this.showSearchHistory = this.searchHistory.slice(0, idx);
          } else {
            this.showSearchHistory = this.searchHistory;
          }
        });
    },
    handleOpenClick() {
      this.showMoreHis = !this.showMoreHis;
      if (this.showMoreHis) {
        this.showSearchHistory = this.searchHistory;
      } else {
        this.toggleHistoryData();
      }
    },
    getHotPositionList() {
      getHotPositionList()
        .then((res) => {
          if (res.code == 200) {
            this.hotPositionList = res.data;
          } else {
            this.hotPositionList = [];
          }
        })
        .catch((err) => {})
        .finally(() => {});
    },
    async handleResultClick(item, tag) {
      if (tag == "search") {
        this.keyword = "";
        this.isSearching = false;
        this.saveHistory(item.positionName);
      }
      let tagTitle = item.positionName || item.tagTitle || "";
      let positionId = item.ylPositionId || item.positionId || "";
      let parentName = item.parentName || item.parentTitle || "";
      let topName = item.topName || item.topTitle || "";
      let params = `positionName=${tagTitle}&positionId=${positionId}&parentTitle=${parentName}&topTitle=${topName}`;
      this.addPositionTopicPointFn(2,positionId);
      //请求接口看是否走新页面
      const templateId = await this.getPositionTemplateFn(positionId);
      if (templateId == 6) {
        uni.navigateTo({
          url: `/pagesSub/careerNewPositionDictionary/positionDetail?${params}`,
        }); 
      } else {
        uni.navigateTo({
          url: `/pagesSub/careerNew/positionDictionary/positionDetail?${params}`,
        });
      }
      // uni.navigateTo({
      //   url: `/pagesSub/careerNew/positionDictionary/positionDetail?${params}`,
      // });
    },
    async getPositionTemplateFn(positionId) {
      const res = await getPositionTemplate({positionId: positionId});
      if (res.code == 200) {
        return res.data.templateId;
      } else {
        return 0;
      }
    },
    handleSearchBlur() {
      // this.isSearching = false;
    },
    handleSearch(e, tag) {
      if (!e) {
        this.isSearching = false;
        return;
      }
      if (tag) {
        this.saveHistory(e);
      }
      const params = { matchName: e, pageNo: 1, pageSize: 999 };
      matchPositionListNew(params)
        .then((res) => {
          if (res.code == 200) {
            this.isSearching = true;
            const list = res.data.map((item, index) => {
              return this.changeText(item);
            });
            this.searchResultList = list;
          } else {
          }
        })
        .finally(() => {});
    },
    changeText(item) {
      return this.filterHighlight(item, this.keyword);
    },
    /**
     * 关键字高亮处理
     * @param { String } text - 文本
     * @param { String } key - 关键字
     */
    filterHighlight(item, key) {
      let textList = item.positionName.split("");
      let keyList = key.split("");
      let list = [];
      for (let i = 0; i < textList.length; i++) {
        let obj = {
          deep: false,
          val: textList[i],
        };
        list.push(obj);
      }
      for (let k = 0; k < keyList.length; k++) {
        list.forEach((_item) => {
          if (
            _item.val === keyList[k] ||
            _item.val.toLowerCase() === keyList[k].toLowerCase()
          ) {
            _item.deep = true;
          }
        });
      }

      item.filterList = list;
      return item;
    },
    // 历史记录相关
    handleDeleteClick() {
      this.searchHistory = [];
      this.showSearchHistory = [];
      uni.removeStorageSync("searchPosHistory");
    },
    handleTagClick(keyword) {
      console.log(keyword);
      this.keyword = keyword;
      //   this.isSearched = true;
      this.handleSearch(keyword);
    },

    saveHistory(keyword) {
      let index = this.searchHistory.findIndex((item) => item.text == keyword);
      if (index > -1) {
        this.searchHistory.splice(index, 1);
      }
      let history = JSON.parse(uni.getStorageSync("searchPosHistory") || "[]");
      if (history.length >= 15) {
        history = history.splice(0, 14);
      }
      if (this.searchHistory.length >= 15) {
        this.searchHistory = this.searchHistory.splice(0, 14);
        this.showSearchHistory = this.showSearchHistory.splice(0, 14);
      }
      this.searchHistory.unshift({ text: keyword });
      // this.showSearchHistory.unshift({ text: keyword });
      history.unshift({ text: keyword });
      history = this.unique(history);
      uni.setStorageSync("searchPosHistory", JSON.stringify(history));
    },
    // 对搜索历史去重
    unique(arr) {
      let newArr = [];
      arr.forEach((i, v) => {
        let flag = true;
        newArr.forEach((item) => {
          if (i.text == item.text) flag = false;
        });
        flag ? newArr.push(i) : newArr;
      });
      return newArr;
    },
  },
};
</script>

<style lang='scss' scoped>
::v-deep .u-hairline-border::after {
  border: none !important;
}
.wrapper {
  width: 100vw;
  min-height: 100vh;
  background: #fff;
  .header {
    position: relative;
    display: flex;
    flex-direction: column;
    align-items: center;
    background-color: #fff;
    .search {
      display: flex;
      padding: 28rpx 32rpx;
      border-radius: 18px;
      ::v-deep.u-content {
        padding: 0 20rpx 0rpx 32rpx;
      }
      ::v-deep.u-close-wrap {
        transform: scale(1.3);
      }
      .library-u-search {
        flex: 1;
        width: 686rpx;
        height: 72rpx;
      }
    }
    .searchResult {
      width: 100%;
      background-color: #fff;
      bottom: -120rpx;
      height: calc(100vh - 260rpx);
      overflow: scroll;
      .resultList {
        overflow: scroll;
        padding-bottom: 48rpx;
        .resultItem {
          padding: 36rpx 32rpx;
          border-bottom: 1px solid #f5f5f5;
          &:last-of-type {
            border-bottom: 0;
          }
          .resultTitle {
            font-size: 30rpx;
            font-family: PingFangSC-Regular, PingFang SC;
            font-weight: 400;
            line-height: 40rpx;
            margin-bottom: 16rpx;
            .light {
              color: #f75a3e;
            }
          }
          .resultDesc {
            font-size: 26rpx;
            font-family: PingFangSC-Regular, PingFang SC;
            font-weight: 400;
            color: #888888;
            line-height: 40rpx;
          }
        }
      }
    }
    .noneResult {
      display: flex;
      flex-direction: column;
      align-items: center;
      width: 100%;
      border-radius: 8rpx;
      font-size: 28rpx;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      margin-top: 130rpx;
      .empty_image {
        width: 400rpx;
        height: 400rpx;
      }
      .empty-title {
        color: #bfbfbf;
        line-height: 40rpx;
      }
    }
  }
  .beforeSearch {
    .searchBox {
      height: calc(100vh - 266rpx);
    }
  }
  .searchHistoryContainer {
    margin-top: 30rpx;
    padding: 0 32rpx;
    .historyTitle {
      display: flex;
      justify-content: space-between;
      align-items: center;
      height: 56rpx;
      margin-bottom: 24rpx;
      .left {
        width: 128rpx;
        height: 56rpx;
        font-size: 32rpx;
        font-family: PingFang-SC-Bold, PingFang-SC;
        font-weight: bold;
        color: #222222;
        line-height: 54rpx;
      }

      .right {
        display: flex;
        justify-content: center;
        align-items: center;
        width: 60rpx;
        .deleteButton {
          margin-right: 10rpx;
        }
        .deleteIcon {
          width: 40rpx;
          height: 40rpx;
        }
      }
    }
    .historyContent {
      display: flex;
      flex-wrap: wrap;
      .hisItem {
        display: inline-block;
        font-size: 28rpx;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #333333;
        padding: 12rpx 16rpx;
        background: #f1f1f1;
        margin-right: 32rpx;
        margin-bottom: 24rpx;
        border-radius: 4rpx;
        line-height: 24rpx;
      }
      image {
        display: inline-block;
        width: 70rpx;
        height: 48rpx;
      }
    }
  }
  .topHot {
    margin: 40rpx 32rpx 100rpx;
    border: 2px solid #fff2ef;
    .title {
      image {
        width: 32rpx;
        height: 32rpx;
        margin-right: 16rpx;
      }
      display: flex;
      padding: 30rpx 28rpx;
      font-size: 32rpx;
      font-family: PingFang-SC-Heavy, PingFang-SC;
      font-weight: 800;
      color: #ff7731;
      line-height: 36rpx;
      background: linear-gradient(
        180deg,
        #ffebe7 0%,
        rgba(255, 255, 255, 0) 100%
      );
      border-radius: 8rpx;
    }
    .hotList {
      margin-top: 16rpx;
      margin-bottom: 48rpx;
      padding: 0 28rpx;
      .hotItem {
        display: flex;
        align-items: center;
        font-family: PingFang-SC-Heavy, PingFang-SC;
        font-size: 28rpx;
        margin-bottom: 24rpx;
        .sort {
          font-weight: 500;
          color: #999999;
          width: 44rpx;
          text-align: center;
        }
        .info {
          display: flex;
          flex-direction: column;
          margin-left: 16rpx;
          font-weight: 400;
          .descT {
            color: #222222;
            width: 560rpx;
          }
          .desc {
            width: 560rpx;
            margin-top: 4rpx;
            color: #a2a5b3;
            font-size: 24rpx;
          }
        }
        .origin {
          color: #ff6d00;
        }
      }
    }
  }
}
.ellipsis {
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow: hidden;
}
::v-deep .u-mode-light-primary {
  color: #555555 !important;
  border: none !important;
}
::v-deep .u-size-default {
  font-size: 24rpx !important;
}
::v-deep .u-content,
::v-deep .u-input {
  background-color: #f5f5f5 !important;
}
.high-light {
  // display: inline-block;
  width: 100%;
  .light {
    color: $high-light;
  }
}
::v-deep .u-icon__img {
  height: 40rpx !important;
  width: 40rpx !important;
}
</style>
